package org.scc.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.scc.model.Prayer;
import org.scc.service.PrayerService;
import org.scc.vo.PageVO;

public class PrayerAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private PrayerService prayerService;
	
	private Prayer prayer;
	
	public PrayerAction(){
		prayerService = new PrayerService();
	}
	
	public void findUserPrayers(){
		PageVO<Prayer> pageVO = prayerService.findByUser(getCurrentUser().getId(), getRowBeginIndex(), rows);
		responeString(getMyPrayerJSON(pageVO));
	}
	
	private String getMyPrayerJSON(PageVO<Prayer> pageVO){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		JSONObject obj = null;
		JSONArray arr = new JSONArray();
		List<Prayer> prayers = pageVO.getData();
		for(Prayer p : prayers){
			obj = new JSONObject();
			obj.put("id", p.getId() );
			obj.put("content", p.getContent() );
			obj.put("date", p.getDateText(sdf) );
			obj.put("status", p.getStatusText() );
			obj.put("scope", p.getScopeText() );
			
			arr.add(obj);
		}
		obj = new JSONObject();
		obj.put("total", pageVO.getTotal());
		obj.put("rows", arr);
		
		return obj.toString();
	}

	public String initEditPage(){
		if(id != 0){
			prayer = prayerService.load(id);
		}
		return SUCCESS;
	}
	
	public void editPrayer(){
		if(prayer.getId() == 0){
			prayer.setDate(new Date() );
			prayer.setStatus(Prayer.STATUS_ING);
			prayer.setUser(getCurrentUser());
			prayerService.add(prayer);
		} else {
			Prayer oldPrayer = prayerService.load(prayer.getId());
			oldPrayer.setContent(prayer.getContent());
			oldPrayer.setScope(prayer.getScope());
			prayerService.update(oldPrayer);
		}
		responseSuccess();
	}
	
	public void deletePrayers(){
		prayerService.delete(ids);
		responseSuccess();
	}
	public Prayer getPrayer() {
		return prayer;
	}

	public void setPrayer(Prayer prayer) {
		this.prayer = prayer;
	}
	
}
